package validator;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import command.ItemForm;

@Component
public class ItemFormValidator implements Validator {

	private static final long MAX_FILE_SIZE = 1048576L;
	
	@Override
	public boolean supports(Class<?> clazz) {
		return ItemForm.class.equals(clazz);
	}
	
	@Override
	public void validate(Object target, Errors errors) {
		ItemForm form = (ItemForm) target;
		if(form.getName()==null){
			errors.rejectValue("name", "empty");
		}else{
			if(form.getName().isEmpty()){
				errors.rejectValue("name", "empty");
			}else if(form.getName().length()>100){
				errors.rejectValue("name", "tooLong");
			}
		}
		if(form.getPrecio()<=0 && !errors.hasFieldErrors("precio")){
			errors.rejectValue("precio", "negativeorzero");
		}
		if(form.getCount()<=0  && !errors.hasFieldErrors("count")){
			errors.rejectValue("count", "negativeorzero");
		}
		if(form.getDescription()==null){
			errors.rejectValue("description", "empty");
		}else{
			if (form.getDescription().isEmpty()){
				errors.rejectValue("description", "empty");
			}else if(form.getDescription().length()>200){
				errors.rejectValue("description", "tooLong");
			}
		}
		if (form.getCategory()==null){
			errors.rejectValue("category", "empty");
		}
		if (form.getImage() != null	&& !form.getImage().isEmpty()) {
			if (form.getImage().getContentType() != null) {
				if (!form.getImage().getContentType().contains("image")) {
					errors.rejectValue("image", "type");
				}
			}
			if (form.getImage().getSize() > MAX_FILE_SIZE) {
				errors.rejectValue("image", "size");
			}
		}	
	}
}